package org.system.core.security.handle;

import com.alibaba.fastjson2.JSON;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.system.core.common.Result;
import org.system.core.enums.ResultCodeEnum;
import org.system.core.utils.ServletUtils;
import org.system.core.utils.StringUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;

/**
 * @author baoRoot
 * 认证失败处理类 返回未授权
 */
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -8970718410437077606L;

    @Override
    public void commence(
            HttpServletRequest request,
            HttpServletResponse response,
            AuthenticationException e
    ) throws IOException {
        ServletUtils.renderString(response, JSON.toJSONString(
                        Result.fail(ResultCodeEnum.AUTHORITY_ERROR.getCode(),
                        StringUtil.format(ResultCodeEnum.AUTHORITY_ERROR.getMessage(), request.getRequestURI()), null)));
    }
}
